import axios from 'axios'
import { Message } from 'element-ui'

// 创建 axios 实例，使用环境变量
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,  // 从环境变量获取基础路径
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (!res.success) {
      Message({
        message: res.message || '请求失败',
        type: 'error',
        duration: 3000
      })
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res
  },
  error => {
    Message({
      message: error.message || '网络错误',
      type: 'error',
      duration: 3000
    })
    return Promise.reject(error)
  }
)

// 封装请求方法
const handleRequest = (method) => (url, data = null) => {
  const config = {
    url,
    method
  }
  
  if (['get', 'delete'].includes(method)) {
    config.params = data
  } else {
    config.data = data
  }

  return service(config)
}

// 导出请求方法
export const request = {
  get: handleRequest('get'),
  post: handleRequest('post'),
  put: handleRequest('put'),
  delete: handleRequest('delete')
}

export default service 